package com.tengju.data.infrastructure.repository;

import com.tengju.data.domain.model.report.DataNameEnum;
import com.tengju.data.domain.model.report.DataVersionRepository;
import com.tengju.data.infrastructure.persistence.mybatis.dataobject.DataVersionDO;
import com.tengju.data.infrastructure.persistence.mybatis.mapper.tengju.custom.DataVersionDOCustomMapper;
import com.tengju.data.infrastructure.persistence.mybatis.mapper.tengju.generate.DataVersionDOMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;

@Repository
public class DataVersionRepositoryImpl implements DataVersionRepository {

    @Resource
    DataVersionDOCustomMapper dataVersionDOCustomMapper;

    @Resource
    DataVersionDOMapper dataVersionDOMapper;

    @Override
    public Integer getDataVersion(DataNameEnum dataName) {
        if (dataName == null) {
            return null;
        }
        return dataVersionDOCustomMapper.getVersionByName(dataName.getName());
    }

    @Override
    public void saveVersion(DataNameEnum dataName, int version) {
        if (dataName == null) {
            return;
        }
        DataVersionDO dataVersionDO = new DataVersionDO();
        Date now = new Date();
        dataVersionDO.setDataName(dataName.getName());
        dataVersionDO.setVersion(version);
        dataVersionDO.setCreateTime(now);
        dataVersionDO.setUpdateTime(now);
        DataVersionDO existVersionDO = dataVersionDOCustomMapper.getVersionDOByName(dataName.getName());
        if (existVersionDO == null) {
            dataVersionDOMapper.insertSelective(dataVersionDO);
            return;
        }
        if (existVersionDO.getVersion() >= version) {
            return;
        }
        existVersionDO.setVersion(version);
        existVersionDO.setUpdateTime(now);
        dataVersionDOMapper.updateByPrimaryKeySelective(existVersionDO);
    }

}
